package servlet;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "Servlet11", value = "/getCode")
public class Servlet11 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //让浏览器5秒自动刷新一次;
        response.setHeader("refresh","5");
        BufferedImage bufferedImage = new BufferedImage(48, 20, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,48,20);
        //drawRect画矩形框，fillRect画矩形
        graphics.setColor(Color.BLUE);
        graphics.setFont(new Font("宋体",Font.BOLD,18));
//        将验证码画出来:
//        1.使用giveCode()生成一个验证码；
        String code = giveCode();
//        2.将验证码用画笔画出来
        graphics.drawString(code,3,18);
        graphics.dispose();
        //添加响应头，清除浏览的缓存功能
        //告诉浏览器，这个请求用图片的方式打开
         response.setContentType("image/jpeg");
        // 设置过期的时间期限
        response.setDateHeader("expires",-1);
        //网站存在缓存，不让浏览器缓存
         response.setHeader("Cache-Control","no-cache");
         response.setHeader("Pragma","no-cache");
        //os是输出流（输出的目的地)
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage,"jpg",os);


    }

    private static String giveCode(){
        int n = new Random().nextInt(10000);// [0,9998]
        String num = String.valueOf(n);//字符串形式的数字
        //将string转换为StringBuffer类型，因StringBuffer长度可变
        StringBuffer sb = new StringBuffer(num);
        for (int i=0;i<4-num.length();i++){
            sb.append("0");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(giveCode());
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
